
package com.epam.android.training.day6;

import android.app.ListActivity;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;

import java.util.ArrayList;
import java.util.List;

/**
 * View to show data from custom content provider
 * 
 * @author Natallia_Kukharchyk
 */
public class MyContentView extends ListActivity {

  private final List<String> myStrings = new ArrayList<String>();

  private final static String columns[] = new String[] {
      MyInfo.Info._ID, MyInfo.Info.INFO_TEXT
  };

  private final static Uri myUri = MyInfo.Info.CONTENT_URI;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // filling with some data
    for (int i = 0; i < 5; i++) {
      insertRecord("sometext" + i);
    }
    displayRecords();

  }

  /**
   * Displaying record in a list view in form :id text
   */
  private void displayRecords() {
    Cursor cur = managedQuery(myUri, columns, null, null, null);
    if (cur.moveToFirst()) {
      String id = null;
      String userName = null;
      do {
        // Get the field values
        id = cur.getString(cur.getColumnIndex(MyInfo.Info._ID));
        userName = cur.getString(cur.getColumnIndex(MyInfo.Info.INFO_TEXT));
        myStrings.add(id + " " + userName);
      } while (cur.moveToNext());
    }

    ListAdapter adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, myStrings);
    setListAdapter(adapter);
  }

  private void insertRecord(String userName) {
    ContentValues values = new ContentValues();
    values.put(MyInfo.Info.INFO_TEXT, userName);
    getContentResolver().insert(MyInfo.Info.CONTENT_URI, values);
  }

}
